<?php
/**
 * 解析移库订单-数据入库
 *（Logic）
 */
namespace App\Logic\Amazon\Api\Parse;

use App\Models\Amazon\FbaRemovalOrderDetail;
class GetFbaFulfillmentRemovalOrderDetailData
{
    public static function exe($lines,$accountId){
        if(!$accountId)return 2;
        if(!is_array($lines))return 2;
        $i = 0;
        $count = 0;
        try{
            foreach($lines as $line){
                $flag = self::_addRemovalOrderDetail($line,$accountId);
                $flag && $count++;
                $i++;
            }
        }catch (\Exception $e){
            report($e);
        }
        return $i == $count ? 1 : 2;
    }

    /**
     * @param $line
     * @param $accountId
     * @return bool
     */
    private static function _addRemovalOrderDetail($line,$accountId){
        $requestDate = gmdate('Y-m-d H:i:s',strtotime($line['request-date']));
        $lastUpdatedDate = gmdate('Y-m-d H:i:s',strtotime($line['last-updated-date']));
        $re = FbaRemovalOrderDetail::query()
            ->updateOrCreate(
                [
                    'account_id' => $accountId,
                    'order_id' => $line['order-id'],
                    'sku' => $line['sku']
                ],
                [
                    'request_date' => $requestDate,
                    'order_type' => $line['order-type'], //订单类型：(Disposal,Liquidations)
                    'order_status' => $line['order-status'], //状态：(Pending(待处理),Completed(已完成))
                    'last_updated_date' => $lastUpdatedDate,
                    'fnsku' => $line['fnsku'],
                    'disposition' => $line['disposition'], //处置方式：(Sellable(可销售的), Unsellable(不可二次销售的))
                    'requested_quantity' => $line['requested-quantity'] ?: 0, //请求数量
                    'cancelled_quantity' => $line['cancelled-quantity'] ?: 0, //取消数量
                    'disposed_quantity' => $line['disposed-quantity'] ?: 0, //处理数量
                    'shipped_quantity' => $line['shipped-quantity'] ?: 0, //发运数量
                    'in_process_quantity' => $line['in-process-quantity'] ?: 0, //在处理数量
                    'removal_fee' => $line['removal-fee'] ?: 0, //移库费用
                    'currency' => $line['currency'] ?: null,
                ]);
        return !$re ? false : true;
    }
}
